
#include "latex_math.h"
#include "parser.tab.h"
#include <math.h>

void yyerror(const char*);

double factorial(double fi)
{
    int f = (int)fi;
	int n = 1;
	for(int i = 2;i<=f;i++)
		n = n*i;
	return (float)n;
}

double binom(double fx, double fy)
{
    int x = (int)fx;
    int y = (int)fy;
    if((double)x != fx || (double)y != fy)
      {
        yyerror("only integers in binomials.");
      }
	if(y < 0)
		return 0;
	if(y > x)
		return 0;
	if(x < 0)
		return 0;

	int max = x-y;
	if(y > x-y)
		max = y;
	int min = x - max;

	int result = 1;
	for(int i = max+1;i<= x;i++)
		result = result*i;
	for(int i = 2;i<= min;i++)
		result = result/i;

	return (double)result;
}

double multinom(double x, double* y)
{
	double count = y[0];
	double sum = 0;
	for(int i = 1;i<=count;i++)
		sum += y[i];
	if(sum != x)
		yyerror("multinomial does not add up");

	int answer = factorial(x);
	for(int i = 1;i<=count;i++)
		answer = answer/factorial(y[i]);
	
	return answer;
}

double expo(double b, double p)
{
  if(b == 0)
  {
    if(p <= 0)
      yyerror("0^p is only defined for positive p");
  }

  if(b < 0)
  {
    if(p != (float)((int)p))
    {
      yyerror("negative numbers must be raised to integral powers");
    }
  }

  return pow(b,p);
}
